package ru.ifmo.ipimenov.ewf_svn.standalone.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.UserProvider;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.User;
import ru.ifmo.ipimenov.ewf_svn.standalone.service.UserService;
import ru.ifmo.ipimenov.ewf_svn.standalone.service.exceptions.UserAuthenticationFailedException;
import ru.ifmo.ipimenov.ewf_svn.standalone.service.impl.UserServiceImpl;
import ru.ifmo.ipimenov.ewf_svn.standalone.view.gui.MainForm;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author: Ilya Pimenov
 * Scartel Starlab company
 */
public class LoginAction implements ActionListener {
    /**
     * Logger for all purposes
     */
    private static Log log = LogFactory.getLog(LoginAction.class);

    private JTextField username = null;
    private JPasswordField password = null;
    private JFrame loginForm = null;

    public LoginAction(JTextField username, JPasswordField password, JFrame loginForm) {
        this.username = username;
        this.password = password;
        this.loginForm = loginForm;
    }

    public void actionPerformed(ActionEvent e) {
        log.info("Logging in ...");
        UserService us = new UserServiceImpl();
        String uName = username.getText();
        String pwd = password.getText();
        try {
            User u = us.load(uName, pwd);
            UserProvider.init(u);
            loginForm.dispose();

            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        } catch (UserAuthenticationFailedException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame frame = new MainForm();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);
    }
}
